package guoanmaker.operator.business.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.OperatorNewsList;
import guoanmaker.operator.business.model.OperatorNewsType;
import guoanmaker.operator.business.model.OperatorRefuseRecord;
import guoanmaker.operator.business.repository.OperatorNewsListRepository;
import guoanmaker.operator.business.repository.OperatorNewsTypeRepository;

/**
 *  
 *
 * @ClassName: OperatorNewsListService 
 * @Description: OperatorNewsListService 
 * @author: huZhaoyu 
 * @date 2017/6/28 下午2:56 
 */
@Service
public class OperatorNewsListService implements OperatorNewsListServiceInterface {
    private final OperatorNewsListRepository operatorNewsListRepository;
    @PersistenceContext
	private EntityManager manager;
    
    @Autowired
    private OperatorNewsTypeRepository operatorNewsTypeRepository;

    @Autowired
    public OperatorNewsListService(OperatorNewsListRepository operatorNewsListRepository) {
        this.operatorNewsListRepository = operatorNewsListRepository;
    }

    @Transactional
    public int saveNewsList(OperatorNewsList operatorNewsList) {
    	String newsTitle=operatorNewsList.getNewsTitle();
		String jpql="select r from OperatorNewsList r where r.newsTitle=:newsTitle";
		Query query=manager.createQuery(jpql).setParameter("newsTitle", newsTitle);
		List<OperatorNewsList> list=query.getResultList();
		if(list!=null&&list.size()>0){
			return -1;
		}
		String newsTypeName=operatorNewsList.getNewsType();
		if(newsTypeName!=null&&!newsTypeName.equals("")){
			String jpql1="select r from OperatorNewsType r where r.newsTypeName=:newsTypeName";
			Query query1=manager.createQuery(jpql1).setParameter("newsTypeName", newsTypeName);
			List<OperatorNewsType> list1=query1.getResultList();
			OperatorNewsType operatorNewsType=null;
			if(list1!=null&&list1.size()>0){
				operatorNewsType=list1.get(0);
			}
			else{
				return -2;
			}
			int count=operatorNewsType.getStatus()+1;
			String tid=operatorNewsType.getId();
			String jpql2="update  OperatorNewsType r  set r.status=:count where r.id=:tid";
			Query query2=manager.createQuery(jpql2).setParameter("count", count).setParameter("tid", tid);
			int n=query2.executeUpdate();
			if(n>0){
				operatorNewsList.setCreateDate(new Date());
				operatorNewsList.setUpdateDate(new Date());
				operatorNewsListRepository.save(operatorNewsList);
				return 1;
			}
		}
		else{
			operatorNewsList.setCreateDate(new Date());
			operatorNewsList.setUpdateDate(new Date());
			operatorNewsListRepository.save(operatorNewsList);
			return 1;
		}
        return 0;
    }

    @Override
    public List<OperatorNewsList> getAllNewsList() {
        return operatorNewsListRepository.findAll();
    }

    @Override
    public Page<OperatorNewsList> getAllNewsListByPage(Integer page, Integer size) {
    	Sort sort = new Sort(Sort.Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
        return operatorNewsListRepository.findAll(pageable);
    }

    @Transactional
    public void deleteNewsListById(String id) {
    	OperatorNewsList operatorNewsList=operatorNewsListRepository.getOne(id);
        operatorNewsListRepository.delete(id);
        String jpql="update  OperatorNewsType r  set r.status=r.status-1 where r.newsTypeName=:oldnewtype";
		Query query=manager.createQuery(jpql).setParameter("oldnewtype", operatorNewsList.getNewsType());
		query.executeUpdate();   
    }

    @Override
    public OperatorNewsList getNewsListById(String id) {
        return operatorNewsListRepository.findOne(id);
    }

    @Override
    public Page<OperatorNewsList> getTieleAndUrl(Integer page, Integer size) {
    	
    	
    	Page<OperatorNewsList> newlists=operatorNewsListRepository.getTieleAndUrl(new PageRequest(page, size,new Sort(Sort.Direction.DESC, "createDate")));
    	/*for(OperatorNewsList newl:newlists){
    		
    		OperatorNewsType operatorNewsType=operatorNewsTypeRepository.findOne(newl.getNewsType());
    		if(operatorNewsType!=null){
    		newl.setNewsType(operatorNewsType.getNewsTypeName());
    		}else{
    			newl.setNewsType("无");
    		}*/
    	/*}*/
    	return newlists;
    }
    
    @Override
    public Map getpcNewList(Integer page, Integer size) {
    	Map<String,Object> remep=new HashMap<String,Object>();
    	
    	Page<OperatorNewsList> newlists=operatorNewsListRepository.getTieleAndUrl(new PageRequest(page, size,new Sort(Sort.Direction.DESC, "createDate")));
    	List<OperatorNewsList> allNewlists=operatorNewsListRepository.getNewList();
    	int count=0;
    	if(allNewlists.size()>0){
    		count=allNewlists.size();
    	}
    	remep.put("newlists", newlists);
    	remep.put("count", count);
    	return remep;
    }
    
    
    
    @Override
    public List<OperatorNewsList> getNewsListByNewType(String newsType) {
        return operatorNewsListRepository.getNews(newsType);
    }
    
    public Map<String,Object> getAllNewsListByStautsPage(Integer page,Integer size,Integer status,String newsTitle,String newsCreater,String StrartCreateDate,
    		String endCreateDate,String StrartNewsDate,String endNewsDate){
    	newsTitle=newsTitle==null?"":newsTitle;
    	newsCreater=newsCreater==null?"":newsCreater;
		Map<String,Object> map=new HashMap<String,Object>();
		String jpql="select new guoanmaker.operator.business.modelnobind.OperatorNewsListMove(r.id,r.newsTitle,r.newsCreater,r.photoPath,"
				+ "r.url,r.createDate,r.updateDate,r.newsDate,r.status,r.newsInfo,r.newsInstruction,r.newsType,u.id,u.username) "
				+ "from OperatorNewsList r left join r.oeratorUser u where r.status=:status and r.newsTitle like :newsTitle "
				+ "and r.newsCreater like :newsCreater order by r.createDate desc";
		Date date1=null;
		Date date2=null;
		Date date3=null;
		Date date4=null;
		if(StrartCreateDate!=null&&!StrartCreateDate.equals("")){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				date1=format.parse(StrartCreateDate);
				jpql+=" and r.createDate >= :StrartCreateDate ";
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(endCreateDate!=null&&!endCreateDate.equals("")){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				date2=format.parse(endCreateDate);
				jpql+=" and r.createDate <= :endCreateDate ";
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(StrartNewsDate!=null&&!StrartNewsDate.equals("")){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				date3=format.parse(StrartNewsDate);
				jpql+=" and r.newsDate >= :StrartNewsDate ";
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(endNewsDate!=null&&!endNewsDate.equals("")){
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				date4=format.parse(endNewsDate);
				jpql+=" and r.newsDate <= :endNewsDate ";
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		Query query = manager.createQuery(jpql).setParameter("newsTitle", "%"+newsTitle+"%").setParameter("newsCreater", "%"+newsCreater+"%").setParameter("status", status);
		if(jpql.indexOf("and r.createDate >= :StrartCreateDate")>-1){
			query.setParameter("StrartCreateDate", date1);
		}
		if(jpql.indexOf("and r.createDate <= :endCreateDate")>-1){
			query.setParameter("endCreateDate", date2);
		}
		if(jpql.indexOf("and r.newsDate >= :StrartNewsDate")>-1){
			query.setParameter("StrartNewsDate", date3);
		}
		if(jpql.indexOf("and r.newsDate <= :endNewsDate")>-1){
			query.setParameter("endNewsDate", date4);
		}
		int count=query.getResultList().size();
		List<OperatorRefuseRecord> list=query.setMaxResults(size)
				.setFirstResult(page*size)
				.getResultList();
		map.put("count", count);
		map.put("list", list);
    	return map;
    }
    
    @Override
    @Transactional
	public int updateStautsNewsList(String id, Integer stauts) {
		String jpql="update OperatorNewsList o set o.status=:stauts,o.updateDate=:updateDate";
		/*if(stauts==1){
			jpql+=",o.newsDate=:newsDate ";
		}*/
		jpql+=" where o.id=:id";
		Query query = manager.createQuery(jpql).setParameter("stauts",stauts).setParameter("id",id).setParameter("updateDate",new Date());
		/*if(stauts==1){
			query.setParameter("newsDate",new Date());
		}*/
		return query.executeUpdate();
	}

    @Transactional
	public int updateNewList(OperatorNewsList operatorNewsList){
		String newsTitle=operatorNewsList.getNewsTitle();
		String jpql="select r from OperatorNewsList r where r.newsTitle=:newsTitle";
		Query query=manager.createQuery(jpql).setParameter("newsTitle", newsTitle);
		List<OperatorNewsList> list=query.getResultList();
		if(list!=null&&list.size()>0){
			OperatorNewsList newList=list.get(0);
			if(newList.getId().equals(operatorNewsList.getId())){
				String newsType=operatorNewsList.getNewsType();
				if(!newsType.equals(newList.getNewsType())){
					String newsTypeName=operatorNewsList.getNewsType();
					String jpql2="update  OperatorNewsType r  set r.status=r.status+1 where r.newsTypeName=:newsTypeName";
					Query query2=manager.createQuery(jpql2).setParameter("newsTypeName", newsTypeName);
					int n=query2.executeUpdate();
					if(n>0){
						String id=operatorNewsList.getId();
						OperatorNewsList operatorNews=operatorNewsListRepository.getOne(id);
						String oldnewtype=operatorNews.getNewsType();
						String jpql3="update  OperatorNewsType r  set r.status=r.status-1 where r.newsTypeName=:oldnewtype";
						Query query3=manager.createQuery(jpql3).setParameter("oldnewtype", oldnewtype);
						int a=query3.executeUpdate();
						if(a==0){
							return 0;
						}
					}
					else{
						return -2;
					}
				}
				String stid=operatorNewsList.getId();
				OperatorNewsList operatorNews=operatorNewsListRepository.getOne(stid);
				operatorNewsList.setOeratorUser(operatorNews.getOeratorUser());
				operatorNewsList.setCreateDate(operatorNews.getCreateDate());
				operatorNewsList.setStatus(operatorNews.getStatus());
				operatorNewsList.setUpdateDate(new Date());
				operatorNewsListRepository.save(operatorNewsList);
				return 1;
			}
			else{
				return -1;
			}
		}
		else
		{
			String id=operatorNewsList.getId();
			OperatorNewsList operatorNews=operatorNewsListRepository.getOne(id);
			String newsType=operatorNews.getNewsType();
			if(!newsType.equals(operatorNewsList.getNewsType())){
				String newsTypeName=operatorNewsList.getNewsType();
				String jpql2="update  OperatorNewsType r  set r.status=r.status+1 where r.newsTypeName=:newsTypeName";
				Query query2=manager.createQuery(jpql2).setParameter("newsTypeName", newsTypeName);
				int n=query2.executeUpdate();
				if(n>0){
					String jpql3="update  OperatorNewsType r  set r.status=r.status-1 where r.newsTypeName=:newsType";
					Query query3=manager.createQuery(jpql3).setParameter("newsType", newsType);
					int a=query3.executeUpdate();
					if(a==0){
						return 0;
					}
				}
				else{
					return -2;
				}
			}
			operatorNewsList.setOeratorUser(operatorNews.getOeratorUser());
			operatorNewsList.setCreateDate(operatorNews.getCreateDate());
			operatorNewsList.setStatus(operatorNews.getStatus());
			operatorNewsList.setUpdateDate(new Date());
			operatorNewsListRepository.save(operatorNewsList);
			return 1;
		}
	}

	@Override
	public List<OperatorNewsList> getNewsList() {
		// TODO Auto-generated method stub
		return operatorNewsListRepository.getNewList();
	}
    
}
